<template>
	<view class="page_main">

		<view class="loading-overlay" v-if="showLoading1">
			<div class="loader"></div>
		</view>

		<z-paging ref="paging" v-model="optionRecord" @query="queryList" :use-page-scroll="false">
			<topNav :title="title + '/USDT'">
				<template v-slot:right>
					<image v-if="!favoriteShow" @click="handleRightImgClick" class="collect"
						src="/static/home/collect.svg" />
					<image v-else @click="handleRightImgClick" class="collect" src="/static/home/collect-a.svg" />
				</template>
			</topNav>

			<view class="base_box">
				<view class="ratio_item">
					<image class="icon" :src="stockDetail.logo" mode=""></image>
					<view class="desc">
						<view class="label">{{ stockDetail.lastPrice }}</view>
						<view class="value"
							:style="{ color: parseFloat(stockDetail.changePercent) >= 0 ? '#06E2E1' : '#FF568E' }">
							{{
								stockDetail.changePercent }}</view>
					</view>
				</view>
				<view class="shuzhi_item">
					<view class="num">O:{{ stockDetail.open }}</view>
					<view class="num">H:{{ stockDetail.high }}</view>
					<view class="num">L:{{ stockDetail.low }}</view>
					<view class="num">C:{{ stockDetail.close }}</view>
				</view>
			</view>

			<div class="charts_box">
				<!-- 图表工具栏 -->
				<view class="chart_toolbar">
					<view class="time_buttons">
						<view v-for="item in timeButtons" :key="item.resolution"
							:class="['time_btn', { active: currentTimeFrame === item.resolution }]"
							@click="changeTimeFrame(item.resolution)">
							{{ item.label }}
						</view>

						<view :class="['time_btn', 'control_btn', 'fenshi_btn', { active: isTimeChartMode }]"
							@click="toggleTimeChart">
							<image :src="isTimeChartMode ? '/static/home/select-fenshi.svg' : '/static/home/fenshi.svg'"
								class="control_icon fenshi_img" />
						</view>

						<view class="control_btn zhibiao_btn time_btn" @click="showIndicators">
							<image src="/static/home/zhibiao.svg" class="control_icon" />
						</view>
					</view>

					<view class="chart_controls">

					</view>
				</view>

				<!-- k线图 -->
				<trade-view :decimal="formatBalance(stockDetail.lastPrice)?.decimal"
					@klineDataUpdate="handleKlineDataUpdate" ref="tradeRef" priceChartWidth="361" priceChartHeight="200"
					macdChartWidth="381" macdChartHeight="85" :idtemp="id"></trade-view>
			</div>
			<view class="tabs_box">
				<view class="tabs_list" v-for="(item, index) in tabs" @click="tabsChange(index)" :key="index">
					<view :class="current == index ? 'tabs_name active' : 'tabs_name'">
						{{ item.name }}
						<view class="line" v-if="current == index"></view>
					</view>
				</view>
			</view>

			<view class="list_box">
				<view class="list_item" v-for="(item, index) in optionRecord" :key="item.id" @click="goDetail(item)">
					<view class="list_title">
						<view class="title">{{ item.productName }}/USDT</view>

						<view class="" v-if="current == 0">
							<image v-if="item.direction == 1" class="icon" src="/static/store/up.svg" />
							<image v-if="item.direction == 2" class="icon" src="/static/store/down.svg" />
						</view>

						<view class="" v-if="current == 1">
							<image v-if="item.status == 1" class="icon" src="/static/store/up.svg" />
							<image v-if="item.status == 2" class="icon" src="/static/store/down.svg" />
							<view v-if="item.status == 3" class="ping">{{ $t('平') }}</view>
						</view>

						<view class="time_process" v-if="current == 0">
							<view class="process">
								<view class="process_line"
									:style="'width:' + formatCountdown(getRemainingTime(item.id)) / item.second * 100 + '%;'">
								</view>
							</view>
							{{ formatCountdown(getRemainingTime(item.id)) }}s
						</view>

						<view class="time_process" v-else>
							<view class="process">
								<view class="process_line" :style="'width:' + 100 + '%;'">
								</view>
							</view>
							{{ $t('结束') }}
						</view>

					</view>
					<view class="list_desc">
						<view class="desc">
							<view class="label">{{ $t("开仓价格") }}</view>
							<view class="value">{{ item.buyPrice }}</view>
						</view>
						<view class="desc">
							<view class="label">{{ $t("下单额") }}</view>
							<view class="value">{{ item.amount }}</view>
						</view>
						<view class="desc">
							<view class="label">{{ $t("收益率") }}</view>
							<view class="value success" v-if="item.profitRatio > 0">{{ item.profitRatio }}%</view>
							<view class="value error" v-if="item.profitRatio < 0">{{ item.profitRatio }}%</view>
							<view class="value normal" v-if="item.profitRatio == 0">{{ item.profitRatio }}%</view>
						</view>
						<view class="desc">
							<view class="label">{{ $t("浮动收益") }}</view>
							<view class="value success" v-if="item.profit > 0">{{ item.profit }}</view>
							<view class="value error" v-if="item.profit < 0">{{ item.profit }}</view>
							<view class="value normal" v-if="item.profit == 0">{{ item.profit }}</view>
						</view>
					</view>
				</view>
			</view>
		</z-paging>


		<view class="operate_box">
			<view class="btn operate_up" @click="openBuy(1)">
				{{ $t("买涨") }}
			</view>
			<view class="btn operate_down" @click="openBuy(2)">
				{{ $t("买跌") }}
			</view>
		</view>

		<!-- 购买弹窗 -->
		<up-popup :show="showBuy" zIndex="500" closeOnClickOverlay bgColor="transparent" :round="78"
			@close="showBuy = false">
			<view class="buy_dialog" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
				@touchend="handleTouchEnd"
				:style="{ transform: `translateX(${swipeOffset}px)`, transition: swipeTransition }">
				<view class="top_line"></view>
				<view class="top_base">
					<view class="info">
						<image class="icon" src="@/static/home/btc.svg" mode=""></image>
						<view class="desc">
							<view class="label">{{ stockDetail.name }}</view>
							<view class="value"
								:style="{ color: parseFloat(stockDetail.changePercent) >= 0 ? '#06E2E1' : '#FF568E' }">
								{{
									stockDetail.changePercent }}</view>
						</view>
					</view>
					<view class="val_box">
						<view class="label">{{ stockDetail.lastPrice }}</view>
						<view class="value">
							{{ $t("买入方向") }}
							<image v-if="buyType == 1" class="icon up" src="/static/store/up.svg" />
							<image v-if="buyType == 2" class="icon down" src="/static/store/down.svg" />
						</view>
					</view>
				</view>
				<!-- 选择时间 -->
				<view class="profit_list">
					<view :class="timeCurrent == index ? 'list_item active' : 'list_item'"
						v-for="(item, index) in stockConfigList" :key="index" @click="timeClick(index, item)">
						<view class="time">{{ item.minute }} s</view>
						<view class="ratio">{{ $t("收益率") }}：{{ item.rate }}%</view>
						<view class="limit">({{ $t("限额") }}{{ item.minAmount }} - {{ item.maxAmount
						}})</view>
					</view>
				</view>
				<view class="have_balance">
					<view class="balance">
						{{ $t("可用余额") }}： {{ balance }}
						<text>USDT</text>
					</view>
					<view class="expected"> {{ $t("预期收益") }}： {{ expectIncome }} </view>
				</view>
				<view class="input_num_box">
					<view class="cost">{{ $t("费用") }}： {{ profit }}</view>
					<view class="wapper_box">
						<view class="input">
							<up-input type="digit" fontSize="28rpx" inputAlign="center" color="#fff" v-model="buyNum" />
						</view>
					</view>
					<image class="operate_btn" src="/static/home/max.svg" @click="handleMax" />
					<image class="operate_btn" src="/static/home/jian.svg" @click="handleReduce" />
					<image class="operate_btn" src="/static/home/jia.svg" @click="handleAdd" />
				</view>

				<!-- 购买金额 -->
				<view class="zhang" v-if="buyType == 1">
					<view class="money-step">
						<up-steps :current="calculateStepCurrent()" inactiveColor="rgb(255, 255, 255)"
							activeColor="rgb(31, 189, 242)">
							<up-steps-item :title="((index - 1) * 25) + '%'" v-for="index in 5" :key="index">
								<template #icon>
									<text :class="[calculateStepCurrent() >= (index - 1) ? 'slot-icon2' : 'slot-icon0']"
										@click="setMoneyByStep(index - 1)">
									</text>
								</template>
							</up-steps-item>
						</up-steps>
					</view>
				</view>
				<view class="die" v-else>
					<view class="money-step">
						<up-steps :current="calculateStepCurrent()" inactiveColor="#fff"
							activeColor="rgb(255, 86, 142)">
							<up-steps-item :title="((index - 1) * 25) + '%'" v-for="index in 5" :key="index">
								<template #icon>
									<text :class="[calculateStepCurrent() >= (index - 1) ? 'slot-icon2' : 'slot-icon0']"
										@click="setMoneyByStep(index - 1)">
									</text>
								</template>
							</up-steps-item>
						</up-steps>
					</view>
				</view>

				<view :class="[buyType == 1 ? 'confirm' : 'confirm eror', disBuyBtn ?'disabled' : '']"  @click="handleConfirm">
					{{ buyType == 1 ? $t("确认买涨") : $t("确认买跌") }}
				</view>
			</view>
		</up-popup>
		<view class="fuzzy_mask" v-if="showBuy"> </view>
		<view class="safe_area"></view>

		<PopupTip v-bind="popupState" @update:show="onPopupUpdate" @close="onPopupClose" />
	</view>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import TradeView from '@/components/TradeView/index.vue'
import { useI18n } from "vue-i18n";
import { reqOptionGetOrderPage, reqGetStockConfigList, reqGetStockDetail, reqPostFee, reqPostSubmit, reqGetOrderStatus } from "../../api/Stock/stock";
import { formatBalance, toast } from "../../utils/tool";
import { favoritesCreate, favoritesdelete } from "../../api/Market";
import PopupTip from "../../components/popupTip/popupTip.vue";
import { createPopupState } from '@/utils/popup.js'
import { reqGetUserGet } from "../../api/Member";
import socket from "../../utils/socket";

const { t, locale } = useI18n();


const paging = ref(null);

// 创建弹窗状态
const {
	popupState,
	showError,
	showLoading,
	hidePopup
} = createPopupState();

// 定义顶部显示的股票名称
const title = ref('');

// 定义显示的股票的id
const id = ref(0);

// 定义添加进入图标倒计时和控制变量
const showLoading1 = ref(true);

// 定义进入图标倒计时
const countdown = ref(2);

// 定义tabs显示的index
const current = ref(0);

// 定义用户信息
const balance = ref(0);

// 定义产品详情详情
const stockDetail = ref({});

// 定义收藏品Id
const favouriteId = ref(0);

// 定义控制时候收藏
const favoriteShow = ref(false);

// 定义持仓记录
const optionRecord = ref([]);

// 定义买涨买跌 1 买涨  2 买跌
const buyType = ref(1);

// 定义购买弹窗显示隐藏
const showBuy = ref(false);

// 定义购买股票时间
const stockConfigList = ref([]);

// 定义购买股票选择时间
const timeCurrent = ref(0);

// 定义选择的秒数
const stockTime = ref(0);

// 定义购买股票金额
const buyNum = ref(0);

// 定义购买股票最大金额
const maxMoney = ref(0);

// 定义购买股票最小金额
const minMoney = ref(0);

// 定义预期收益
const expectIncome = ref(0);

// 定义收益率
const incomeRate = ref(0);

// 定义手续费
const profit = ref(0);

// 定义订单返回的结果
const status = ref(3);

// 使用 reactive 存储每个持仓中项目的剩余时间
const countdownData = reactive({});

// 存储所有定时器的引用
const countdownTimers = ref({});

const tradeRef = ref(null);

// 定义判断购买按钮是否禁用
const disBuyBtn = ref(false);

// 添加滑动相关变量
const touchStartX = ref(0);
const touchStartY = ref(0);
const touchMoveX = ref(0);
const touchMoveY = ref(0);
const isSwiping = ref(false);

const swipeOffset = ref(0);
const swipeTransition = ref('transform 0.1s ease-out');

// 定义k线类型
const klineType = ref('stock-kline-day');

// 定义tab
const tabs = ref([
	{
		name: "持仓中",
		code: "",
	},
	{
		name: "已平仓",
		code: "",
	},
]);

// 参数传递
onLoad((option) => {
	id.value = option.id;
	title.value = option.title;
})

// 点击跳转订单明细回调
const goDetail = (item) => {
	uni.navigateTo({
		url: "/pages/store/detail?id=" + item.id + "&current=" + current.value,
	});
}

// 点击tabs切换回调
const tabsChange = (index) => {
	current.value = index;
	paging.value.reload();
}

// 获取产品详情
const getStockDetail = async () => {

	try {
		const result = await reqGetStockDetail(id.value);

		stockDetail.value = Object.assign(result, {
			// 商品代码
			productCode: result.productCode.slice(0, 3) + '/' + result.productCode.slice(3),
			// 涨跌幅
			changePercent: result.stockInfo.market.changePercent,
			open: result.stockInfo.market.open,
			preClose: result.stockInfo.market.preClose,
			volume: Math.floor(result.stockInfo?.market?.volume),
			low: result.stockInfo.market.low,
			high: result.stockInfo.market.high,
			close: result.stockInfo.market.close,
			amount: Math.floor(result.stockInfo?.market?.amount),
			// 当前价格
			lastPrice: result.stockInfo.market.lastPrice,
			klines: result.stockInfo
				? result.stockInfo.klines?.map((line) => {
					return {
						time: Number(line.timestamp),
						value: line.close ? Number(Number(line.close).toFixed(2)) : 0,
					};
				})
				: [],
		});
		// 收藏按钮切换
		favoriteShow.value = result.favourite;
		// 收藏商品的id
		favouriteId.value = stockDetail.value.favouriteId
	} catch (error) {
		showError(t(error.message), t('请重试'))
	}

}

// 点击收藏按钮回调
const handleRightImgClick = async () => {
	// index == 0 想要收藏状态
	let param = {
		stockId: id.value
	}
	if (favoriteShow.value == false) {
		const result = await favoritesCreate(param);
		if (result) {
			favoriteShow.value = true;
			// idtemp2.value = result.data
			getStockDetail();
			toast(t('收藏成功'));
		} else {
			toast(result.msg, 'error');
		}
	} else {
		const result = await favoritesdelete({ favouriteId: favouriteId.value });
		if (result) {
			favoriteShow.value = false;
			getStockDetail();
			toast(t('取消收藏成功'));

		} else {
			toast(result.msg, 'error');
		}
	}
}

// 点击买涨买跌按钮回调  
const openBuy = (type) => {
	// buyType 1 买涨  2 买跌
	buyType.value = type;
	// 显示购买弹窗
	showBuy.value = true;
}

// 弹窗
//#region 
// 期权

// 获取购买股票详情
const getStockConfigList = async () => {
	const result = await reqGetStockConfigList(id.value);
	if (result[0]) {
		stockConfigList.value = result;
		maxMoney.value = result[0].maxAmount;
		minMoney.value = result[0].minAmount;
		stockTime.value = result[0].minute;
		expectIncome.value = Number(result[0].rate / 100 * buyNum.value).toFixed(2);
		incomeRate.value = result[0].rate;
	}
}

// 点击时间
const timeClick = (index, item) => {
	timeCurrent.value = index;
	maxMoney.value = item.maxAmount;
	minMoney.value = item.minAmount;
	stockTime.value = item.minute;
	expectIncome.value = item.rate / 100 * buyNum.value;
	incomeRate.value = item.rate;
	getFee();

};


watch(buyNum, (newValue, oldValue) => {
	if (newValue <= maxMoney.value && newValue >= minMoney.value) {
		// 获取管理费
		expectIncome.value = (incomeRate.value / 100 * buyNum.value).toFixed(2);
		getFee();
	}
})

// 点击最大金额回调
const handleMax = () => {
	buyNum.value = maxMoney.value;
}

// 点击减号金额
const handleReduce = () => {
	if (buyNum.value - 100 >= minMoney.value) {
		buyNum.value -= 100;
	}
}
// 点击加号金额
const handleAdd = () => {
	if (buyNum.value + 100 <= maxMoney.value) {
		buyNum.value += 100;
	}
}


// 获取实名认证信息
const authentication = ref();

// 获取用户信息
const getUserInfo = async () => {
	const result = await reqGetUserGet();
	balance.value = result.availableBalance;
	authentication.value = result.authStatus;
};

// 计算步骤进度 - 修改为按区间判断
const calculateStepCurrent = () => {
	// 如果 moneyValue 为 0 或未定义，返回 -1 (表示没有进度)
	if (!buyNum.value || buyNum.value < minMoney.value) return -1;

	// 如果达到最大值，全部高亮（返回最大索引4）
	if (buyNum.value >= maxMoney.value) return 4;

	// 如果是最低金额，只高亮第一个
	if (buyNum.value === minMoney.value) return 0;

	// 计算中间的三个值
	const range = maxMoney.value - minMoney.value;
	const step = range / 4; // 分为4个区间

	// 计算当前处于第几个区间
	const progress = buyNum.value - minMoney.value;
	return Math.floor(progress / step);
};

// 根据步骤设置金额值
const setMoneyByStep = (step) => {
	// 确保 minMoney 和 maxMoney 已定义
	if (!minMoney.value || !maxMoney.value) return;

	// 根据步骤计算对应的金额值
	if (step === 0) {
		// 第一个按钮，设为最小金额
		buyNum.value = minMoney.value;
	} else if (step === 4) {
		// 最后一个按钮，设为最大金额
		buyNum.value = maxMoney.value;
	} else {
		// 中间的按钮，按比例计算金额
		const range = maxMoney.value - minMoney.value;
		const stepValue = (range / 4) * step;
		buyNum.value = minMoney.value + stepValue;
	}
};

// 获取手续费回调
const getFee = async () => {
	const params = {
		productId: id.value,
		amount: buyNum.value,
		direction: buyType.value,  // 1 买 2 卖
		second: stockTime.value
	}

	const result = await reqPostFee(params);
	profit.value = result.fee;
};


//#endregion

// 获取订单纪录
const queryList = async (pageNo, pageSize) => {
	try {
		const params = {
			pageNo,
			pageSize,
			status: current.value  // 0 未结算   1 已结算
		}


		// 获取期权订单纪录
		const result = await reqOptionGetOrderPage(params);

		// 只有在 tabIndex == 0 时才启动倒计时
		if (current.value == 0) {
			// 启动每个项目的倒计时
			result.list.forEach(item => {
				startCountdown(item.id, item.createTime, item.second);
			});
		}

		paging.value.complete(result.list);
	} catch (error) {
		paging.value.complete(false);
	}
}

// 点击确认按钮回调
const handleConfirm = async () => {
	// 禁用购买按钮
			disBuyBtn.value = true;
	// 判断是否实名认证
	if (authentication.value != 2) return showError(t('请完成实名认证'));
	// 获取秒数
	// 购买期权
	const params = {
		productId: id.value,
		amount: buyNum.value,
		direction: buyType.value,
		second: stockTime.value
	}
	// 获取期权单号
	try {
		const result = await reqPostSubmit(params);
		timeCurrent.value = 0

		getOrderStatus(result);
	} catch (error) {
		showError(t(error.message), t('请重试'));
	}

}

// 定义期权购买是否成功
const getOrderStatus = async (orderSn) => {
	const timer = setInterval(async () => {
		try {
			const result = await reqGetOrderStatus(orderSn);
			status.value = result.status.status;
			// 如果 result 为 1，停止定时器
			if (result.status.status === 1) {
				clearInterval(timer);
				showLoading(t('提交下单'), t('查看持仓...'));
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/store/store'
					});

				}, 2000)

				// 订单状态确认，可以重新加载数据或更新UI
				paging.value.reload();
			}
			// 可以添加其他状态处理
			else if (result.status.status === 2) {
				// 订单失败等情况
				clearInterval(timer);
				toast(result.status.message); // 订单创建失败提示
				// successShow.value = false;
			}
		} catch (error) {

			clearInterval(timer);
			showError(t(error.message), t('请重试'));


		}finally {
			disBuyBtn.value = false;

		}
	}, 1000);

	// 可选：设置最大等待时间，避免定时器无限运行
	setTimeout(() => {
		clearInterval(timer);
	}, 30000); // 30秒后自动停止
}

// 格式化倒计时显示
const formatCountdown = (seconds) => {
	if (seconds <= 0) return "0";
	return seconds.toString();
};

// 获取指定项目的剩余时间
const getRemainingTime = (itemId) => {
	return countdownData[itemId] || 0;
};

// 计算初始剩余时间
const calculateRemainingTime = (createTime, totalSeconds) => {
	// createTime 是毫秒时间戳，转换为秒
	const createTimeInSeconds = Math.floor(createTime / 1000);
	// 计算结束时间 = 创建时间 + 持续时间
	const endTime = createTimeInSeconds + parseInt(totalSeconds);
	// 当前时间
	const now = Math.floor(Date.now() / 1000);
	// 剩余时间
	const remainingTime = endTime - now;

	return remainingTime > 0 ? remainingTime : 0;
};

// 启动倒计时
// 修改 startCountdown 函数
const startCountdown = (itemId, createTime, totalSeconds) => {
	// 只有在 current == 0 时才启动倒计时
	if (current.value != 0) return;

	// 初始化剩余时间
	countdownData[itemId] = calculateRemainingTime(createTime, totalSeconds);

	// 如果已有定时器，先清除
	if (countdownTimers.value[itemId]) {
		clearInterval(countdownTimers.value[itemId]);
	}

	// 设置新的定时器
	countdownTimers.value[itemId] = setInterval(() => {
		// 更新剩余时间
		countdownData[itemId] = calculateRemainingTime(createTime, totalSeconds);

		// 如果倒计时结束，清除定时器并刷新列表
		if (countdownData[itemId] <= 0) {
			clearInterval(countdownTimers.value[itemId]);
			delete countdownTimers.value[itemId];
			delete countdownData[itemId];
			// 倒计时结束后重新请求数据
			paging.value.reload();
		}
	}, 1000);
};

// 清除所有定时器
const clearAllCountdowns = () => {
	Object.values(countdownTimers.value).forEach(timer => {
		clearInterval(timer);
	});
	countdownTimers.value = {};
	// 清空倒计时数据
	Object.keys(countdownData).forEach(key => {
		delete countdownData[key];
	});
};


// 触摸开始
const handleTouchStart = (e) => {
	const touch = e.touches[0];
	touchStartX.value = touch.clientX;
	touchStartY.value = touch.clientY;
	isSwiping.value = true;
};

// 触摸移动
const handleTouchMove = (e) => {
	if (!isSwiping.value) return;

	const touch = e.touches[0];
	touchMoveX.value = touch.clientX;
	touchMoveY.value = touch.clientY;
};

// 触摸结束
const handleTouchEnd = (e) => {
	if (!isSwiping.value) return;

	const deltaX = touchMoveX.value - touchStartX.value;
	const deltaY = Math.abs(touchMoveY.value - touchStartY.value);

	// 判断是否为水平滑动（左右滑动）
	// 水平滑动距离大于50像素，且垂直滑动距离小于30像素
	if (Math.abs(deltaX) > 50 && deltaY < 30) {
		// 右滑关闭（从左向右滑动）
		if (deltaX > 0) {
			showBuy.value = false;
		}
		// 左滑关闭（从右向左滑动）
		else {
			showBuy.value = false;
		}
	}

	// 重置状态
	isSwiping.value = false;
	touchStartX.value = 0;
	touchStartY.value = 0;
	touchMoveX.value = 0;
	touchMoveY.value = 0;
};


// 添加图表控制相关数据
const currentTimeFrame = ref('1D');
const isTimeChartMode = ref(false);

// 时间按钮配置
const timeButtons = ref([
	{ label: '1m', resolution: '1' },
	{ label: '5m', resolution: '5' },
	{ label: '30m', resolution: '30' },
	{ label: '60m', resolution: '60' },
	{ label: '1D', resolution: '1D' },
	{ label: '1W', resolution: '1W' },
	{ label: '1M', resolution: '1M' }
]);

// 修改时间周期
const changeTimeFrame = (resolution) => {
	currentTimeFrame.value = resolution;

	// 调用 TradingView 的方法切换时间周期
	if (tradeRef.value && tradeRef.value.widget) {
		const widget = tradeRef.value.widget;
		widget.chart().setResolution(resolution, () => {
		});

		// 如果当前是分时图模式，保持分时图
		if (isTimeChartMode.value) {
			widget.chart().setChartType(3); // 面积图（分时图）
		} else {
			widget.chart().setChartType(1); // K线图
		}
	}
};

// 切换分时图模式
const toggleTimeChart = () => {
	isTimeChartMode.value = !isTimeChartMode.value;

	if (tradeRef.value && tradeRef.value.widget) {
		const widget = tradeRef.value.widget;
		const resolution = currentTimeFrame.value;

		if (isTimeChartMode.value) {
			// 切换到分时图
			widget.chart().setChartType(3); // 面积图
			widget.chart().setResolution(resolution, () => { });
		} else {
			// 切换到K线图
			widget.chart().setChartType(1); // 蜡烛图
			widget.chart().setResolution(resolution, () => { });
		}
	}
};

// 显示指标
const showIndicators = () => {
	if (tradeRef.value && tradeRef.value.widget) {
		const widget = tradeRef.value.widget;
		widget.chart().executeActionById('insertIndicator');
	}
};

// 在组件卸载时清除所有定时器
onUnmounted(() => {
	clearAllCountdowns();
});

// 接收k线图传来的类型
const handleKlineDataUpdate = (e) => {
	klineType.value = e;
}

// 连接k线
const socket1 = new socket();

const onMessage = (data) => {
	if (data.type === klineType.value) {
		try {
			const content = JSON.parse(JSON.parse(data.content));
			if (!content || !content.id) return;
			if (content.id != id.value) return
			const newKline = {
				time: content.klines[0]?.timestamp || 0,
				value: content.klines[0]?.close || 0
			};
			stockDetail.value.lastPrice = content.market?.lastPrice;
			stockDetail.value.changePercent = content.market?.changePercent;

			stockDetail.value.open = content.market?.open;
			stockDetail.value.preClose = content.market?.preClose;
			stockDetail.value.volume = Math.floor(content.market?.volume);
			stockDetail.value.low = content.market?.low;
			stockDetail.value.high = content.market?.high;
			stockDetail.value.amount = Math.floor(content.market?.amount);

		} catch (e) {
			console.error('Error parsing message:', e);
		}
	}
}

socket1.on('message', onMessage)

// 在onMounted中启动倒计时并预加载数据
onMounted(async () => {
	// 立即开始获取数据
	await Promise.all([
		getStockDetail(),
		getStockConfigList(),
		getUserInfo()
	]);

	// 初始化K线图
	if (tradeRef.value) {
		tradeRef.value.init('', "1D", locale);
	}

	// 开始倒计时
	const timer = setInterval(() => {
		countdown.value -= 1;

		if (countdown.value <= 0) {
			clearInterval(timer);
			showLoading1.value = false;
		}
	}, 1000);

	socket1.doOpen()
	socket1.on('open', () => {
		socket1.send({
			"sub": ["market.btcusdt.kline.1min", "market.btcusdt.kline.5min", "market.btcusdt.kline.15min"],
			"id": "id1"
		})
	})
});

// 弹窗事件处理
const onPopupUpdate = (value) => {
	// 确保状态同步
	if (popupState.value) {
		popupState.value.show = value;
	}
};

const onPopupClose = () => {
	hidePopup();
};

</script>

<style lang="scss" scoped>
.page_main {
	width: 100%;
	display: flex;
	align-items: center;
	flex-direction: column;
	min-height: 100vh;

	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #0d0d0f;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
		width: 100%;
		height: 100%;
		/* 背景颜色 */


	}

	.loader {
		width: 50px;
		aspect-ratio: 1.154;
		position: relative;
		background: conic-gradient(from 120deg at 50% 64%, #0000, #32a0ff 1deg 120deg, #0000 121deg);
		animation: l27-0 1.5s infinite cubic-bezier(0.3, 1, 0, 1);
	}

	.loader:before,
	.loader:after {
		content: '';
		position: absolute;
		inset: 0;
		background: inherit;
		transform-origin: 50% 66%;
		animation: l27-1 1.5s infinite;
	}

	.loader:after {
		--s: -1;
	}

	@keyframes l27-0 {

		0%,
		30% {
			transform: rotate(0)
		}

		70% {
			transform: rotate(120deg)
		}

		70.01%,
		100% {
			transform: rotate(360deg)
		}
	}

	@keyframes l27-1 {
		0% {
			transform: rotate(calc(var(--s, 1)*120deg)) translate(0)
		}

		30%,
		70% {
			transform: rotate(calc(var(--s, 1)*120deg)) translate(calc(var(--s, 1)*-5px), 10px)
		}

		100% {
			transform: rotate(calc(var(--s, 1)*120deg)) translate(0)
		}
	}

	.collect {
		width: 42rpx;
		height: 42rpx;
	}

	.base_box {
		margin: 14rpx 34.8rpx 0;
		height: 158rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.ratio_item {
			width: 286rpx;
			height: 84rpx;
			border-radius: 35rpx;
			background: rgb(41, 42, 46);
			box-shadow: inset 0rpx 1.74rpx 3.49rpx rgba(255, 255, 255, 0.11),
				0rpx 6.98rpx 10.47rpx rgba(0, 0, 0, 0.25);
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 33rpx 20rpx;

			.icon {
				width: 84rpx;
				height: 84rpx;
			}

			.desc {
				flex: 1;
				margin-left: 20rpx;
				height: 100%;
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				justify-content: space-between;

				.label {
					background: linear-gradient(160.02deg,
							rgba(6, 226, 225, 1) 0%,
							rgba(50, 160, 255, 1) 74.99%),
						rgba(50, 160, 255, 1);
					font-size: 31rpx;
					font-weight: 500;
					color: rgb(112, 112, 112);
					-webkit-background-clip: text;
					-webkit-text-fill-color: transparent;
				}

				.value {
					font-size: 21rpx;
					font-weight: 400;
					color: rgb(255, 86, 142);
				}
			}
		}

		.shuzhi_item {
			width: 286rpx;
			height: 84rpx;
			border-radius: 35rpx;
			background: rgb(41, 42, 46);
			box-shadow: inset 0rpx 1.74rpx 3.49rpx rgba(255, 255, 255, 0.11),
				0rpx 6.98rpx 10.47rpx rgba(0, 0, 0, 0.25);
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-wrap: wrap;
			padding: 33rpx 20rpx;

			.num {
				width: 50%;
				font-size: 20.93rpx;
				font-weight: 400;
				color: #fff;
			}
		}
	}


	.charts_box {
		margin-top: 12px;
		width: 100%;
		background-color: #0D0D0F;

		.chart_toolbar {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 0 35rpx 12px;
			padding: 10rpx 20rpx;
			border-radius: 9px;
			background-color: rgba(49, 51, 60, 1);
			overflow-x: auto !important;

			box-shadow: inset 0px 1px 2px rgba(255, 255, 255, 0.11), 0px 4px 6px rgba(0, 0, 0, 0.25);

			overflow-y: hidden; // 隐藏纵向滚动
			padding-bottom: 10rpx; // 防止滚动条遮挡内容

			// 隐藏滚动条（可选）
			&::-webkit-scrollbar {
				display: none;
			}

			.time_buttons {
				display: flex;
				gap: 10rpx;

				.time_btn {
					padding: 8rpx 16rpx;
					color: #a4a8ab;
					border-radius: 8rpx;
					font-size: 14px;
					font-weight: 400;
					letter-spacing: 0px;
					line-height: 20.27px;
					color: rgba(255, 255, 255, 1);
					text-align: left;
					vertical-align: top;

					&.active {
						font-size: 14px;
						font-weight: 500;
						letter-spacing: 0px;
						line-height: 20.27px;
						color: rgba(50, 160, 255, 1);
						text-align: left;
						vertical-align: top;
					}

					&:hover {
						font-size: 14px;
						font-weight: 500;
						letter-spacing: 0px;
						line-height: 20.27px;
						color: rgba(50, 160, 255, 1);
						text-align: left;
						vertical-align: top;
					}
				}

				.fenshi_btn {
					image {}
				}

				.control_btn {
					width: 24px !important;
					height: 19px !important;

					

					image {

						width: 24px !important;
						height: 19px !important;
					}
				}
			}

		}

		// TradingView 图表容器样式
		::v-deep(#trade-view) {
			height: 380px !important;
			width: 100% !important;
			background-color: #0D0D0F !important;
		}
	}

	.tabs_box {
		margin-top: 40rpx;
		margin-left: 50rpx;
		height: 42rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;

		.tabs_list {
			position: relative;
			height: 100%;
			color: #808080;
			font-weight: 400;
			font-size: 28rpx;
			text-align: center;
			margin-right: 38rpx;

			.tabs_name {
				display: flex;

				&.active {
					color: #fff;
					font-weight: 700;
					font-size: 28rpx;
				}

				.line {
					position: absolute;
					margin: auto;
					left: 0;
					width: 52rpx;
					top: 42rpx;
					height: 24rpx;
					background: url("@/static/home/tab_bg.svg") no-repeat center;
					background-size: 100% 100%;
				}
			}
		}
	}

	.list_box {
		margin: 49rpx 34.8rpx 100px;

		.list_item {
			margin-bottom: 21rpx;
			padding: 35rpx;
			border-radius: 21rpx;
			background: rgb(41, 42, 46);
			box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
			height: 152rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.list_title {
				display: flex;
				align-items: center;

				.title {
					font-size: 28rpx;
					font-weight: 500;
					color: #fff;
				}

				.ping {
					margin-left: 20rpx;
					width: 35rpx;
					height: 35rpx;
					border-radius: 5.23rpx;
					background: #944131;
					font-size: 21rpx;
					font-weight: 400;
					color: #ff5733;
					text-align: center;
					line-height: 35rpx;
				}

				.icon {
					margin-left: 20rpx;
					width: 35rpx;
					height: 35rpx;
				}

				.time_process {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					font-size: 24rpx;
					font-weight: 500;
					color: #fff;

					.process {
						width: 120rpx;
						height: 7rpx;
						margin: auto 15rpx;
						border-radius: 3.5rpx;
						background: rgb(235, 235, 235);
						overflow: hidden;

						.process_line {
							height: 100%;
							background: linear-gradient(90deg,
									rgba(22, 196, 163, 1) 0%,
									rgba(74, 214, 207, 1) 34.72%,
									rgba(18, 156, 202, 1) 65.97%,
									rgba(2, 123, 217, 1) 100%);
						}
					}
				}
			}

			.list_desc {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-around;

				.desc {
					display: flex;
					flex-direction: column;
					align-items: center;

					.label {
						font-size: 28rpx;
						font-weight: 300;
						color: #fff;
					}

					.value {
						font-size: 24rpx;
						font-weight: 500;
						color: #fff;
						margin-top: 10rpx;

						&.success {
							color: rgb(6, 226, 225);
						}

						&.error {
							color: rgb(255, 87, 51);
						}

						&.normal {
							color: rgb(255, 87, 51);
						}
					}
				}
			}
		}
	}

	.operate_box {
		width: 750rpx;
		height: 157rpx;
		border-radius: 31rpx 31rpx 0rpx 0rpx;
		background: rgba(116, 120, 149, 0.08);
		backdrop-filter: blur(61.05rpx);
		position: fixed;
		margin: auto;
		left: 0;
		right: 0;
		bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		display: flex;
		align-items: center;
		justify-content: space-evenly;
		z-index: 100;

		.btn {
			width: 279rpx;
			height: 87rpx;
			border-radius: 26rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #fff;
			text-align: center;
			line-height: 87rpx;

			&.operate_up {
				background: rgb(50, 160, 255);
			}

			&.operate_down {
				background: rgb(255, 86, 142);
			}
		}
	}

	.buy_dialog {
		width: 100%;
		border-radius: 78rpx 78rpx 0rpx 0rpx;
		background: rgb(41, 42, 46);
		border: 1.74rpx solid rgb(49, 51, 60);
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		padding-bottom: 34.8rpx;

		.top_line {
			position: absolute;
			margin: auto;
			left: 0;
			right: 0;
			top: 20rpx;
			width: 87rpx;
			height: 10rpx;
			box-sizing: border-box;
			border-radius: 5rpx;
			background: rgb(50, 160, 255);
			border: 1.74rpx solid rgb(49, 51, 601);
		}

		.top_base {
			width: 666rpx;
			margin-top: 80rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.info {
				width: 286rpx;
				height: 84rpx;
				border-radius: 35rpx;
				background: rgb(41, 42, 46);
				display: flex;
				align-items: center;
				justify-content: space-between;

				.icon {
					width: 84rpx;
					height: 84rpx;
				}

				.desc {
					flex: 1;
					margin-left: 20rpx;
					height: 100%;
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: center;

					.label {
						font-size: 31rpx;
						font-weight: 700;
						color: #fff;
					}

					.value {
						font-size: 21rpx;
						font-weight: 400;
						color: rgb(255, 86, 142);
					}
				}
			}

			.val_box {
				height: 100%;
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				justify-content: space-between;

				.label {
					font-size: 31.4rpx;
					font-weight: 700;
					color: #fff;
				}

				.value {
					font-size: 24.42rpx;
					font-weight: 400;
					color: rgb(116, 120, 149);
					display: flex;
					align-items: center;

					.icon {
						width: 35rpx;
						height: 35rpx;
						margin-left: 10rpx;
					}
				}
			}
		}

		.profit_list {
			width: 686rpx;
			display: flex;
			margin-top: 10rpx;
			align-items: center;
			justify-content: space-between;
			flex-wrap: wrap;

			.list_item {
				width: 323rpx;
				height: 140rpx;
				opacity: 1;
				border-radius: 14rpx;
				border: 1.74rpx solid rgb(49, 51, 60);
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				justify-content: space-evenly;
				flex-direction: column;

				&.active {
					background: rgb(56, 60, 71);
					border: 1.74rpx solid rgb(49, 51, 60);
					box-shadow: inset 0rpx 1.74rpx 3.49rpx rgba(255, 255, 255, 0.11),
						0rpx 6.98rpx 10.47rpx rgba(0, 0, 0, 0.25);
				}

				.time {
					font-size: 31rpx;
					font-weight: 400;
					color: #fff;
				}

				.ratio {
					font-size: 21rpx;
					font-weight: 400;
					color: #fff;
				}

				.limit {
					font-size: 21rpx;
					font-weight: 400;
					color: rgb(116, 120, 149);
				}
			}
		}

		.have_balance {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 686rpx;
			margin-top: 40rpx;

			.balance {
				font-size: 24rpx;
				font-weight: 400;
				color: #fff;

				text {
					font-size: 21rpx;
				}
			}

			.expected {
				font-size: 24rpx;
				font-weight: 400;
				color: #fff;
			}
		}

		.input_num_box {
			height: 70rpx;
			width: 686rpx;
			display: flex;
			align-items: center;
			margin-top: 40rpx;
			justify-content: space-between;

			.cost {
				width: 143rpx;
				height: 100%;
				opacity: 1;
				border-radius: 35rpx;
				border: 1.74rpx solid rgb(49, 51, 60);
				font-size: 21rpx;
				font-weight: 400;
				color: #fff;
				text-align: center;
				line-height: 70rpx;
			}

			.wapper_box {
				width: 253rpx;
				height: 100%;
				border-radius: 35rpx;
				/* 渐变边框实现 */
				background-origin: border-box;
				background-clip: padding-box, border-box;
				background: linear-gradient(90deg,
						rgba(22, 196, 163, 1) 0%,
						rgba(74, 214, 207, 1) 34.72%,
						rgba(18, 156, 202, 1) 65.97%,
						rgba(2, 123, 217, 1) 100%);
				display: flex;
				align-items: center;
				justify-content: center;

				.input {
					width: 249rpx;
					height: 64rpx;
					background: #292a2e;
					border-radius: 34rpx;
					text-align: center;
					color: #fff;
				}
			}

			.operate_btn {
				width: 70rpx;
				height: 70rpx;
				border-radius: 50%;
				line-height: 70rpx;
				text-align: center;
				font-size: 21rpx;
				font-weight: 400;
				color: #fff;
			}
		}

		.money-step {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 61px;
			margin: 22px 0 30px;





		}

		.zhang {
			width: 100%;

			.slot-icon2 {
				color: #fff;

				border-radius: 50%;
				border: 3px solid rgb(50, 151, 235);
				// 	background: linear-gradient(90deg, #8FDA58 0%, #2A7F11 100%);
				// 	mask: radial-gradient(circle at center,
				// 			transparent 0%,
				// 			transparent calc(50% - 1.5px),
				// 			#fff calc(50% - 1.5px),
				// 			#fff 50%);
				// 	-webkit-mask: radial-gradient(circle at center,
				// 			transparent 0%,
				// 			transparent calc(50% - 1.5px),
				// 			#fff calc(50% - 1.5px),
				// 			#fff 50%);
			}
		}

		.die {
			width: 100%;

			.slot-icon2 {

				border-radius: 50%;
				border: 3px solid rgb(255, 86, 142);

			}
		}

		.slot-icon2 {
			width: 9px;
			height: 9px;
			border: 2px solid rgb(50, 151, 235);
			border-radius: 50%;
			color: #fff;

		}

		.slot-icon0 {
			width: 9px;
			height: 9px;
			// background: #8EE04E;
			border: 1px solid rgb(255, 255, 255);
			border-radius: 50%;
			color: #fff;
		}

		::v-deep .u-text__value--content {
			color: #fff !important;
		}

		::v-deep .u-text__value--main {
			color: #fff !important;
		}

		::v-deep .u-steps-item__line--row {
			// width: 52px !important;
			height: 2px !important;
			// background: #1B7A00 !important;
			// background: linear-gradient(90deg, rgb(12, 216, 229) 0%, rgb(31, 189, 242) 64.58%, rgb(49, 161, 255) 100%);
		}

		::v-deep .u-steps-item__content--row {
			margin-top: 0px !important;
			margin-left: 10px !important;
		}

		::v-deep .u-steps-item__wrapper {
			background-color: #292a2e;
			// width: 20.9rpx !important;
			// height: 20.9rpx !important;
		}

		.confirm {
			width: 570rpx;
			height: 98rpx;
			border-radius: 26rpx;
			font-size: 31rpx;
			font-weight: 500;
			color: #fff;
			background: rgb(50, 160, 255);
			text-align: center;
			line-height: 98rpx;

			&.eror {
				background: rgb(255, 86, 142);
			}
		}

		.disabled {
			pointer-events: none;
			/* 禁止点击事件 */
			background-color: #cccccc;
			color: #333333;
		}
	}

	.safe_area {
		height: 180rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
}

.fuzzy_mask {
	position: fixed;
	margin: auto;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	z-index: 300;
	background: rgba(51, 51, 51, 0.3);
	backdrop-filter: blur(10.47rpx);
}

::v-deep .zp-empty-view-center {
	padding: 0;
	justify-content: start;
	margin-top: -80px;
	margin-bottom: 100px;
}
</style>
